<template>
  <div class="create-commere-order-form">
    <Title title="订单信息" class="mb-16" />
    <el-form
      ref="formRef"
      :model="paramsObj"
      :rules="rules"
      :label-position="showMobilePage?'left':'right'"
      class="edit-order lineHeight32"
      label-width="90px">
      <div class="customer-form">
        <el-row type="flex" class="response-el-row">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="订单渠道">
              <el-select v-model="paramsObj.orderChannel" disabled name="orderChannel" size="small">
                <el-option
                  v-for="item in orderChannelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="销售" prop="market" >
              <selectWithUserLoad
                ref="selectUser"
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                v-model="paramsObj.marketObj"
                :hide-select-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
                :select-data-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
                :multiple="false"
                placeholder="请选择销售"
                value-type="object"
                key-name="id"
                label-name="userName"
                extend-class="create-ip-order-select"
                filterable
                collapse-tags
                @change="marketChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="标题" prop="title">
              <el-input v-model="paramsObj.title" :disabled="isEdit && paramsObj.orderStatus >= 2" name="title" maxlength="200" type="text" size="small" placeholder="标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="IP形象">
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.ipAry"
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                :select-data-list="paramsObj.ipAry || []"
                :loadmore-method="getipFigure()"
                multiple
                placeholder="请选择IP形象"
                value-type="object"
                key-name="ipId"
                label-name="ipName"
                extend-class="ip-image"
                filterable
                collapse-tags
                clearable
                @change="ipFigureChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="价格" prop="price">
              <el-input
                v-model="paramsObj.price"
                :disabled="taxAmountDisabled || (isEdit && paramsObj.orderStatus >= 2)"
                oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
                name="price"
                type="number"
                placeholder="价格"
                size="small"
                @change="numInputChange($event, 'price')"
                @mousewheel.native.prevent />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="来源平台" prop="platformId">
              <el-select v-model="paramsObj.platformId" :disabled="isEdit && paramsObj.orderStatus >= 2" name="orderChannel" size="small" clearable>
                <el-option
                  v-for="item in platformOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="客户名称" prop="clientName">
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.clientObj"
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                :select-data-list="paramsObj.clientObj ?[paramsObj.clientObj] : []"
                :hide-select-list="paramsObj.clientObj && JSON.stringify(paramsObj.clientObj) !== '{}' ?[paramsObj.clientObj] : []"
                :multiple="false"
                :loadmore-method="getClient()"
                placeholder="请选择客户"
                extend-class="client-select-width240"
                value-type="object"
                key-name="id"
                label-name="clientName"
                filterable
                collapse-tags
                clearable
                @change="clientNameChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="paramsObj.orderStatus" size="small">
                <el-option
                  v-for="item in orderStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="订单创建时间" prop="orderCreateTime">
              <el-date-picker
                v-model="paramsObj.orderCreateTime"
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                :picker-options="pickerOptions"
                :clearable="true"
                type="datetime"
                placeholder="请选择订单创建时间"
                value-format="timestamp"
                size="small"
                class="order-time"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="付款时间">
              <el-date-picker
                v-model="paramsObj.payTime"
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                :clearable="true"
                type="datetime"
                placeholder="请选择付款时间"
                value-format="timestamp"
                size="small"
                class="order-time"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="备注" prop="remark">
              <el-input
                :disabled="isEdit && paramsObj.orderStatus >= 2"
                v-model="paramsObj.remark"
                placeholder="备注"
                maxlength="200"
                name="remark"
                type="text"
                size="small"
                clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="订单编号（第三方）" prop="orderNumThirdParty">
              <el-input
                v-model="paramsObj.orderNumThirdParty"
                :maxlength="50"
                placeholder="订单编号（第三方）"
                name="orderNumThirdParty"
                type="text"
                size="small"
                clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="附件" prop="attachment" class="attachment">
              <div class="attachment-container">
                <upAttachment
                  ref="uploadImg"
                  :import-api="'/common/file/upload'"
                  :hide-confirm="true"
                  :is-disabled="isFileDisabled"
                  :file-list="paramsObj.attachment"
                  btn-text="上传文件"
                  @upProgress="upProgress"
                  @complateSetData="complateSetData"
                  @removeFileList="removeFileList" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="发货时间(实际)" prop="actualTime">
              <el-date-picker
                v-model="paramsObj.actualTime"
                :picker-options="pickerOptions"
                :clearable="true"
                type="datetime"
                placeholder="请选择发货时间"
                value-format="timestamp"
                size="small"
                class="order-time"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="发货时间(系统)：" prop="systemTime">
              <span>{{ paramsObj.systemTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import Title from '@/components/Title';
import upAttachment from '@/components/Common/upAttachment/index';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getIpImageList, getClientList } from '@/api/mengliOrder';
import { validateNumber, validateTime, validateIp } from '../validator/validator';
import { mapState } from 'vuex';
import { getSettingList } from '@/api/setting';
import { format } from '@/filters/date';

export default {
  components: { selectWithUserLoad, upAttachment, Title },
  filters: {
    format
  },
  model: {
    prop: 'paramsObj',
    event: 'change'
  },
  props: {
    paramsObj: {
      type: Object,
      default() {
        return {};
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    taxAmountDisabled: {
      type: Boolean,
      default: false
    },
    orderStatus: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      isFileDisabled: false,
      rules: {
        clientName: [{ required: true, trigger: 'change', validator: validateNumber('请选择客户名称') }],
        title: [{ required: true, trigger: 'change', validator: validateNumber('请输入标题') }],
        orderNumThirdParty: [{ required: true, trigger: 'change', validator: validateNumber('请输入订单编号(第三方)') }],
        price: [{ required: true, trigger: 'blur', message: '请输入价格' }],
        warehouseId: [{ required: true, trigger: 'change', validator: validateIp('请选择仓库') }],
        market: [{ required: true, trigger: 'change', validator: validateIp('请选择销售') }],
        goodsCoding: [{ required: true, trigger: 'change', validator: validateNumber('请输入SKU编码') }],
        goodsAttribute: [{ required: true, trigger: 'change', validator: validateNumber('请输入商品属性') }],
        orderStatus: [{ required: true, trigger: 'change', validator: validateNumber('请选择订单状态') }],
        orderCreateTime: [{ required: true, trigger: 'change', validator: validateTime('请选择订单创建时间') }],
        platformId: [{ required: true, trigger: 'change', validator: validateNumber('请选择来源平台') }]
      },
      orderChannelOptions: [{ value: 0, label: '线上' }, { value: 1, label: '线下' }],
      platformOptions: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    ipSeriesName() {
      const ipAry = this.paramsObj.ipAry;
      const name = [];
      if (ipAry && ipAry.length) {
        ipAry.forEach(i => {
          name.push(i.ipSeriesName);
        });
      }
      return name.join(',');
    },
    orderStatusOptions() {
      const ary = [
        { value: 0, label: '等待买家付款', disabled: this.isEdit && this.paramsObj.orderStatus >= 1 },
        { value: 1, label: '买家已付款', disabled: this.isEdit && this.paramsObj.orderStatus >= 2 },
        { value: 2, label: '卖家已发货', disabled: this.isEdit && this.paramsObj.orderStatus >= 3 },
        { value: 3, label: '交易成功', disabled: this.isEdit && this.paramsObj.orderStatus >= 4 },
        { value: 4, label: '交易关闭', disabled: false }
      ];
      return ary;
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const deadline = new Date(year, month - 1, 1, 0, 0, 0);
          return time.getTime() < deadline.getTime();
        }
      };
    }
  },
  created() {
    this.getPlatforms();
  },
  methods: {
    /**
     * 获取下拉数据
     */
    // 获取来源平台
    async getPlatforms() {
      const res = await getSettingList();
      this.platformOptions = res.data.filter(item => {
        return item.name === '萌力星球';
      })[0].item.filter(item => {
        return item.name === '萌力订单-来源平台';
      })[0].item;
    },
    // 获取ip形象
    getipFigure() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.ipName = '';
          if (params.userName) params.ipName = params.userName;
          delete params.userName;
          getIpImageList(params).then(res => {
            const { items } = res.data;
            items.forEach((item) => {
              const ipSeriesName = item.ipSeriesName || '--';
              item.ipName = `${item.ipName}/${ipSeriesName}`;
            });
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    getClient() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.clientName = '';
          if (params.userName) params.clientName = params.userName;
          delete params.userName;
          getClientList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    /**
     * change 事件
     */
    ipFigureChange(item) {
    //   item.map(item => {

    //   });
      // this.paramsObj.ipFigure = item.userName;
      // this.paramsObj.ipFigureId = item.id;
    },
    clientNameChange(item) {
      this.paramsObj.clientName = item.clientName;
      this.paramsObj.clientId = item.id;
      this.paramsObj.clientType = item.clientType;
    },
    marketChange(item) {
      this.paramsObj.market = item.userName;
      this.paramsObj.marketId = item.id;
    },
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.paramsObj[prop] = str;
    },
    // 上传文件
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.paramsObj && this.paramsObj.attachment && this.paramsObj.attachment.length > 0) {
        this.paramsObj.attachment.push(fileList);
      } else {
        this.paramsObj.attachment = [fileList];
      }
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs['formRef'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-commere-order-form {
  & ::v-deep {
    .el-form-item {
      .el-select {
        width: 240px;
      }
      .el-input__inner  {
        width: 240px;
      }
      .el-textarea__inner {
        height: 64px !important;
      }
      .el-form-item__label {
        color: #666;
        height: 32px;
      }
    }
  }
  .indentation-form-item {
    ::v-deep .el-form-item {
      label {
        line-height: 1.2 !important;
      }
    }
  }
}
</style>
<style lang="scss">
.global-select-down.ip-image .el-select-dropdown__item span {
  display: inline-block;
  width: calc(100% - 14px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
<style lang="scss">
.client-select-width240 {
  width: 240px;
}
</style>
